package com.example.es.service;

import com.example.es.entity.Promotion;
import com.example.es.repository.PromotionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class PromotionService {

    @Autowired
    private PromotionRepository promotionRepository;

    @Cacheable(value = "promotions", key = "#id")
    public Optional<Promotion> findById(Long id) {
        return promotionRepository.findById(id);
    }

    @Cacheable(value = "activePromotions")
    public List<Promotion> findActivePromotions() {
        LocalDateTime now = LocalDateTime.now();
        return promotionRepository.findByActiveTrueAndStartTimeBeforeAndEndTimeAfter(now, now);
    }

    @Cacheable(value = "promotionsByType", key = "#type")
    public List<Promotion> findByType(String type) {
        return promotionRepository.findByTypeAndActiveTrue(type);
    }

    @Cacheable(value = "promotionsByDiscount", key = "#minDiscountRate")
    public List<Promotion> findByMinDiscountRate(Double minDiscountRate) {
        return promotionRepository.findByDiscountRateGreaterThanEqualAndActiveTrue(minDiscountRate);
    }

    @Cacheable(value = "promotionSearch", key = "#name + '-' + #type + '-' + #minDiscountRate + '-' + #tags")
    public List<Promotion> searchPromotions(String name, String type, Double minDiscountRate, String tags) {
        return promotionRepository.searchPromotions(name, type, minDiscountRate, tags);
    }

    @Caching(evict = {
        @CacheEvict(value = "promotions", key = "#promotion.id"),
        @CacheEvict(value = "activePromotions", allEntries = true),
        @CacheEvict(value = "promotionsByType", allEntries = true),
        @CacheEvict(value = "promotionsByDiscount", allEntries = true),
        @CacheEvict(value = "promotionSearch", allEntries = true)
    })
    public Promotion save(Promotion promotion) {
        promotion.setUpdatedAt(LocalDateTime.now());
        return promotionRepository.save(promotion);
    }

    @Caching(evict = {
        @CacheEvict(value = "promotions", key = "#id"),
        @CacheEvict(value = "activePromotions", allEntries = true),
        @CacheEvict(value = "promotionsByType", allEntries = true),
        @CacheEvict(value = "promotionsByDiscount", allEntries = true),
        @CacheEvict(value = "promotionSearch", allEntries = true)
    })
    public void deleteById(Long id) {
        promotionRepository.deleteById(id);
    }

    public List<Promotion> findAll() {
        return promotionRepository.findByActiveTrueOrderByCreatedAtDesc();
    }
}